/*
 * @Description: 
 * @Author: Yong
 * @Date: 2021-10-04 15:36:16
 * @LastEditTime: 2021-10-10 21:45:02
 */
import React, { ComponentType } from "react"
import { RouteComponentProps } from "react-router-dom"
import socket from 'socket.io-client'

import styles from "./index.module.scss"
import { Grid, Image, Space, List } from "antd-mobile"
import * as Icons from "antd-mobile-icons"

const userPhoto = require("@assets/images/defaultPhoto.jpg")

import H from "history"
interface Location extends H.Location {
    query: { [key: string]: string }
}
interface IProps extends RouteComponentProps {
    location: Location
}
interface FMLItem {
    avatar?: string
    id?: string
    nickName?: string
    lastTime?: string
    msgCon?: string
    unreadCount?: number
}
interface IStates {
    userInfo: { [key: string]: string }
    applyFriendTotal?: number
    friendMsgList: Array<FMLItem>
}


export default class Home extends React.Component<IProps, IStates> {

    state: IStates = {
        userInfo: JSON.parse(window.localStorage.getItem('userInfo')),
        applyFriendTotal: 0,
        friendMsgList: []
    }

    componentDidMount () {
        // 获取当前用户信息
        // const userInfo = JSON.parse(window.localStorage.getItem('userInfo'))
        // 连接socket / home端
        const HomeSocket = socket('ws://localhost:7001/home', {
            path: '/testPath',
            query: {
                userID: this.state.userInfo.ID
            }
        })

        // 监听socket连接
        HomeSocket.on('connection', (socket) => {
            console.log('服务端连接成功')
        })

        // 监听Home端连接后 初始化页面数据
        HomeSocket.on('initHomeData', data => {
            console.log('initHomeData/data ==>', data)
            this.setState({
                applyFriendTotal: data.applyFriendTotal,
                friendMsgList: data.friendMsgList.list
            })
        })

        // 监听好友申请更新
        HomeSocket.on('updateApplyFriendTotal', data => {
            if (data.toId === this.state.userInfo.ID) {
                console.log('updateApplyFriendTotal/data ==>', data)
                this.setState({
                    applyFriendTotal: data.applyFriendTotal
                })
            }
        })

        // 监听好友消息列表更新
        HomeSocket.on('updateFriendMsgList', data => {
            // 如果更新toId 和当前页面的ID一直才更新好友消息列表
            if (data.toId === this.state.userInfo.ID) {
                console.log('updateFriendMsgList/data ==>', data)
                this.setState({
                    friendMsgList: data.friendMsgList.list
                })
            }
        })
    }

    routeToChatRoom = (item: FMLItem) => {
        // 跳转进入聊天页面 - 发消息
        const friendInfo = {
            ID: item.id,
            U_Avatar: item.avatar,
            U_LoginID: item.nickName,
            U_nickName: item.nickName
        }
        this.props.history.push({ pathname: '/chatRoom', state: { friendInfo } })
    }

    render () {
        const SearchOutline = (Icons as any)['SearchOutline'] as ComponentType
        const AddCircleOutline = (Icons as any)['AddCircleOutline'] as ComponentType
        const { applyFriendTotal, friendMsgList, userInfo } = this.state
        return (
            <div className={styles.home}>
                {/* 头部 */}
                <div className={styles.header}>
                    <Grid columns={5} gap={8} className={styles.grid}>
                        <Grid.Item>
                            <div className={styles["userPhoto"]}>
                                <Image
                                    src={userPhoto}
                                    width={40}
                                    height={40}
                                    fit="cover"
                                    style={{ borderRadius: 4 }}
                                />
                            </div>
                        </Grid.Item>
                        <Grid.Item span={2}>
                            {userInfo.U_LoginID}
                        </Grid.Item>
                        <Grid.Item span={2} className={styles["rightItem"]}>
                            <Space size={15}>
                                <div className={styles.icon}><SearchOutline /></div>
                                <div className={styles.icon} onClick={() => { this.props.history.push('/addFriends') }}><AddCircleOutline /></div>
                            </Space>
                        </Grid.Item>
                    </Grid>
                </div>
                {/* 列表 */}
                <div className={styles.list}>
                    <div className={styles.applyFriend} onClick={() => { this.props.history.push('/friendApplication') }}>
                        好友申请 - {applyFriendTotal}
                    </div>
                    {/* 好友消息列表 */}
                    <h5>好友消息列表</h5>
                    <List>
                        {friendMsgList.map((item, index) => (
                            <List.Item
                                key={index}
                                extra={<ExtraRender data={item} />}
                                prefix={<Image src={userPhoto} style={{ borderRadius: 20 }} fit='cover' width={40} height={40} />}
                                description={`备注：${item.msgCon}`}
                                onClick={() => { this.routeToChatRoom(item) }}
                            >
                                {item.nickName}
                            </List.Item>
                        ))}
                    </List>
                </div>
            </div>
        )
    }
}

type StateType = {}

type propType = {
    data: FMLItem
}
interface ExtraRender {
    state: StateType
    props: propType
}
class ExtraRender extends React.Component {

    render () {
        const { unreadCount, lastTime } = this.props.data
        return (
            <div>
                <p>{lastTime}</p>
                <p>{ unreadCount !== 0 ? `未读消息数 - ${unreadCount}` : '' }</p>
            </div>
        )
    }
}
